package com.igoal.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.igoal.entity.ComponentEnum;
import com.igoal.entity.DataStatus;
import com.igoal.entity.UserTag;

@Repository("userTagDAO")
public class UserTagDAOImpl extends GenericDaoHibernate<UserTag, Long>
		implements UserTagDAO {

	public UserTagDAOImpl() {
		super(UserTag.class);
	}

	public UserTag findByInformation(Long userId, Long tagId,
			ComponentEnum component, Long componentId) {
		DetachedCriteria dc = DetachedCriteria.forClass(UserTag.class);
		dc.add(Restrictions.eq("user.id", userId));
		dc.add(Restrictions.eq("tag.id", tagId));
		dc.add(Restrictions.eq("component", component));
		dc.add(Restrictions.eq("componentId", componentId));
		getByStatus(dc, DataStatus.USING);
		
		List<UserTag> result = findByCriteria(dc, 0, 1);
		if(!result.isEmpty()){
			return result.get(0);
		}
		return null;
	}
	
	public boolean isComponentTagged(Long tagId, ComponentEnum component, Long componentId){
		DetachedCriteria dc = DetachedCriteria.forClass(UserTag.class);
		dc.add(Restrictions.eq("tag.id", tagId));
		dc.add(Restrictions.eq("component", component));
		dc.add(Restrictions.eq("componentId", componentId));
		getByStatus(dc, DataStatus.USING);
		
		int count = countByCriteria(dc);
		return count > 0;
	}
	
	public List<UserTag> getTagsOfComponent(Long componentId, ComponentEnum component){
		DetachedCriteria dc = DetachedCriteria.forClass(UserTag.class);
		dc.add(Restrictions.eq("component", component));
		dc.add(Restrictions.eq("componentId", componentId));
		getByStatus(dc, DataStatus.USING);
		
		return findByCriteria(dc);
	}
	
	public void deleteAllTag(Long componentId, ComponentEnum component){
		String hsql = "Delete UserTag t Where t.component=:comp and t.componentId=:comp_id";
		Query query = getSession().createQuery(hsql);
		query.setString("comp", component.toString());
		query.setLong("comp_id", componentId);
		query.executeUpdate();
	}
}
